using System.Web.UI.WebControls;
using ValidationFramework.Reflection;

namespace ValidationFramework.Web.ASP
{
    internal class ServerWebValidator : BaseValidator
    {
        #region Fields

        private readonly Rule propertyRule;
        private readonly InfoDescriptor infoDescriptor;
        private readonly ServerValidateDelegate serverValidate;

        internal delegate ValidationResult ServerValidateDelegate(Rule propertyRule, InfoDescriptor infoDescriptor);

        #endregion


        #region Constructors

        internal ServerWebValidator(Rule propertyRule, InfoDescriptor infoDescriptor, ServerValidateDelegate serverValidate)
        {
            this.propertyRule = propertyRule;
            this.infoDescriptor = infoDescriptor;
            this.serverValidate = serverValidate;
            EnableClientScript = false;
        }

        #endregion


        #region Methods
		/// <inheritdoc />
        protected override bool EvaluateIsValid()
        {
            var result = serverValidate(propertyRule, infoDescriptor);
            if (result == null)
            {
                return true;
            }
            else
            {
                ErrorMessage = result.ErrorMessage;
                Text = result.ErrorMessage;
                return false;
            }
        }

        #endregion
    }
}